#include <iostream>
#include <string>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;

void Usage(const string proc)
{
    cout << "Usage:\n\t" << proc << " server_ip server_port" << endl;
}

//./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);

    //1.创建socket文件
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        cerr<<"socket error"<<endl;
        exit(2);
    }

    //2.双方直接进行通信
    //构建目标主机socket信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());

    string message;
    while(true)
    {
        cout<<"Please Enter# ";
        getline(cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)(&server),sizeof(server));

        struct sockaddr_in peer;
        bzero(&peer,sizeof(peer));
        socklen_t len=sizeof(peer);
        char buffer[1024];
        ssize_t n=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n>0)
        {
            buffer[n]=0;
            cout<<"server echo# "<<buffer<<endl;
        }
    }
    return 0;
}